package 网络编程.客户端与服务器的请求与响应.TCP流.客户端;

import 网络编程.客户端与服务器的请求与响应.TCP流.服务器.TcpEchoServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        socket = new Socket(serverIp,serverPort);
    }
    public void start(){
        System.out.println("客户端启动");
        Scanner sc = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerNetwork = new Scanner(inputStream);
            while(true){
                System.out.print("输入要发送的内容:");
                String request = sc.next();
                request += "\n";
                outputStream.write(request.getBytes());
                if(!scannerNetwork.hasNext()){
                    break;
                }
                String response = scannerNetwork.next();
                System.out.println(response);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
